package com.dashan.frontend.client.util;

import static com.dashan.Constants.SESSIONID;
import static com.dashan.Constants.USERNAME;

import com.dashan.frontend.client.DashanCookie;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.URL;

public class DashanRequestBuilder extends RequestBuilder {
    
    private String content = "";
    
    public DashanRequestBuilder(String url) {
        super(RequestBuilder.POST, url);
    }
    
    public void addParameter(String name, String value) {
        if (content.compareTo("") == 0) {
            content = URL.encodeComponent(name) + "=" + URL.encodeComponent(value);
        } else {
            content += "&" + URL.encodeComponent(name) + "=" + URL.encodeComponent(value);
        }
    }
    
    public void resetContent() {
        content = "";
    }
    
    public void addUserParam() {
        DashanCookie cookie = DashanCookie.load();
        if (cookie != null) {
            addParameter(USERNAME, cookie.getUserName());
            addParameter(SESSIONID, cookie.getSessionId());
        }
    }
    
    public Request sendRequest(RequestCallback callback) throws RequestException {
        super.setHeader("Content-Type", "application/x-www-form-urlencoded");
        super.setHeader("Accept", "image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
        return super.sendRequest(content, callback);
    }
}
